'''
Created on Mar 25, 2013

@author: LONG HOANG GIANG
'''

import os
import time
import cPickle
import traceback

class CacheManager():
    
    @staticmethod
    def put(filepath, data, expired=86400):
        if not os.path.isdir(os.path.dirname(filepath)): os.makedirs(os.path.dirname(filepath), 0777)
        fp = open(filepath, 'wb')
        cPickle.dump(data, fp)
        fp.close()
        expired = time.time() + expired
        os.utime(filepath, (expired, expired))
    
    @staticmethod
    def remove(path):
        try:
            if os.path.isfile(path):
                os.unlink(path)
        except:
            traceback.print_exc()
    
    @staticmethod
    def get(filepath):
        if os.path.isfile(filepath):
            now = time.time()
            if os.path.getmtime(filepath) < now:
                os.unlink(filepath)
                return None
            try:
                fp = open(filepath, 'rb')
                result = cPickle.load(fp)
                fp.close()
                return result
            except:
                pass
        return None
    
    @staticmethod
    def setLastModified(filepath, expired=86400):
        if os.path.isfile(filepath):
            expired = time.time() + expired
            os.utime(filepath, (expired, expired))
            
        